//
//  DraftItem.m
//  Weibbo
//
//  Created by 李 林刚 on 13-6-30.
//  Copyright (c) 2013年 Omnivores. All rights reserved.
//

#import "DraftItem.h"
#import "NSData+MBBase64.h"
@implementation DraftItem
@synthesize text = _text;
@synthesize imageName = _imageName;
@synthesize isQuotation = _isQuotation;
+ (DraftItem *)plainDraftItem
{
    DraftItem *item = [[DraftItem alloc] init];
    NSMutableAttributedString  *plain = [[[NSMutableAttributedString alloc] initWithString:@""] autorelease];
    [item setText:plain];
    return item;
}
- (BOOL)isPlain
{
    NSMutableAttributedString  *plain = [[[NSMutableAttributedString alloc] initWithString:@""] autorelease];
    return [self.text isEqualToAttributedString:plain];
}
- (BOOL)isImage
{
    if (_imageName.length > 0) {
        return YES;
    }
    return NO;
}
- (id)initWithDictionary:(NSDictionary *)dic
{
    self = [super init];
    if (self)
    {
        if ([dic isKindOfClass:[NSDictionary class]])
        {
            NSData  *textData = [NSData dataWithBase64EncodedString:[dic objectForKey:@"text"]];
            NSMutableAttributedString  *textString = [NSKeyedUnarchiver unarchiveObjectWithData:textData];
            self.text = textString;
            self.imageName = [dic objectForKey:@"image"];
            self.isQuotation = [[dic objectForKey:@"is_promote"] boolValue];
        }
    }
    return self;
}
- (NSMutableDictionary *)toDictionary
{
    NSMutableDictionary  *result = [NSMutableDictionary dictionary];
    
    NSData  *textData = [NSKeyedArchiver archivedDataWithRootObject:self.text];
    NSString  *textString = [textData base64Encoding];
    [result setObject:textString forKey:@"text"];
    if (self.imageName != nil) {
        [result setObject:self.imageName forKey:@"image"];
    }
    [result setObject:[NSString stringWithFormat:@"%d",self.isQuotation] forKey:@"is_promote"];

    return result;
}
- (UIImage  *)getImage
{
    return [UIImage imageWithName:[self imageName]];
}
- (void)setImage:(UIImage *)image
{
    if (self.imageName != nil) {
        [[NSFileManager defaultManager] removeItemAtPath:UIDocumentFile(self.imageName) error:nil];
    }
    NSString  *imageName = [NSString stringWithFormat:@"%d.png",(int)[[NSDate date] timeIntervalSince1970]];
    NSData *imageData = UIImagePNGRepresentation(image);
    [imageData writeToFile:UIDocumentFile(imageName) atomically:YES];
    self.imageName = imageName;
}
-(void)dealloc
{
    UIRelease(_text);
    UIRelease(_imageName);
    [super dealloc];
}

@end
